<!-- isDisabled:0=查看1=修改2=编辑3=协同链接 -->
<template>
  <div>
    <a-spin :spinning="confirmLoading">
      <a-form-model
        ref="ruleForm"
        :model="formInfo"
        :label-col="$global.labelCol"
        :wrapper-col="$global.wrapperCol"
        :disabled="this.isDisabled == '0'"
      >
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="合同名称"
              prop="contractName"
              :rules="$valid.required"
              :maxLength="50"
              :label-width="10"
            >
              <a-input
                v-model="formInfo.contractName"
                placeholder="请输入合同名称"
                :disabled="this.isDisabled == '3'"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="合同编号"
              prop="contractNumber"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-input
                v-model="formInfo.contractNumber"
                placeholder="请输入合同编号"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="采购方式"
              prop="contractProcurementMethodId"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                style="min-width: 100px"
                :showArrow="true"
                v-model="formInfo.contractProcurementMethodId"
                placeholder="请选择采购方式"
              >
                <a-select-option
                  v-for="item in contractProcurementMethodList"
                  :key="item.itemValue"
                  :value="item.itemValue"
                >
                  {{ item.itemText }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="签订日期" prop="signingDate">
              <a-date-picker
                v-model="formInfo.signingDate"
                inputReadOnly
                type="date"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                placeholder="请选择签订日期"
                style="width: 100%"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="关联项目"
              prop="associatedProject"
              :maxLength="50"
            >
              <a-input
                v-model="formInfo.associatedProject"
                placeholder="请输入关联项目"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="关联预算"
              prop="associatedBudget"
              :maxLength="50"
            >
              <a-input
                v-model="formInfo.associatedBudget"
                placeholder="请输入关联预算"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="销售人员"
              prop="salespersonName"
              :maxLength="50"
            >
              <a-input
                v-model="formInfo.salespersonName"
                placeholder="请输入销售人员"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="管理部门"
              prop="administrativeDept"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                style="min-width: 100px"
                :showArrow="true"
                v-model="formInfo.administrativeDept"
                placeholder="请选择管理部门"
              >
                <a-select-option
                  v-for="item in administrativeDeptList"
                  :key="item.itemValue"
                  :value="item.itemValue"
                >
                  {{ item.itemText }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="采购组织形式"
              prop="procurementForm"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                style="min-width: 100px"
                :showArrow="true"
                v-model="formInfo.procurementForm"
                placeholder="请选择采购组织形式"
              >
                <a-select-option
                  v-for="item in procurementFormList"
                  :key="item.itemValue"
                  :value="item.itemValue"
                >
                  {{ item.itemText }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="配置批准单位"
              prop="approvedBy"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-select
                :size="'default'"
                style="min-width: 100px"
                :showArrow="true"
                v-model="formInfo.approvedBy"
                placeholder="请选择配置批准单位"
              >
                <a-select-option
                  v-for="item in approvedByList"
                  :key="item.itemValue"
                  :value="item.itemValue"
                >
                  {{ item.itemText }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">签约方</a-divider>

        <a-table
          :columns="contractPartyColumns"
          :dataSource="contractPartyList"
          :pagination="false"
          bordered
          size="middle"
          rowKey="key"
        >
          <!-- 自定义单元格渲染 - 可编辑单元格 v-for="(row, index) in data" -->
          <template
            v-for="col in editableContractPartyColumns"
            :slot="col.dataIndex"
            slot-scope="text, record, index"
          >
            <div :key="col.dataIndex" class="editable-cell">
              <span v-if="col.dataIndex == 'partyName'">{{ text }} </span>
              <span v-else-if="col.dataIndex == 'institutionName'">
                <span v-if="index == 0">{{ text }}</span>
                <span v-else>
                  <a-select
                    v-model="record[col.dataIndex]"
                    placeholder="请选择供应商"
                    @blur="validateContractPartyField(record, col.dataIndex)"
                    :class="{
                      'error-field':
                        record.errors && record.errors[col.dataIndex],
                    }"
                  >
                    <a-select-option
                      v-for="item in supplierList"
                      :value="item.id + ''"
                    >
                      {{ item.companyName }}</a-select-option
                    >
                  </a-select>
                </span>
              </span>
              <a-input
                v-else
                v-model="record[col.dataIndex]"
                @blur="validateContractPartyField(record, col.dataIndex)"
                :class="{
                  'error-field': record.errors && record.errors[col.dataIndex],
                }"
              />

              <div
                class="error-message"
                v-if="record.errors && record.errors[col.dataIndex]"
              >
                {{ record.errors[col.dataIndex] }}
              </div>
            </div>
          </template>

          <!-- 操作列 - 添加/删除行按钮 -->
          <template slot="action" slot-scope="text, record, index">
            <div class="action-buttons">
              <a-tooltip title="添加一行">
                <a-button
                  type="primary"
                  shape="circle"
                  icon="plus"
                  size="small"
                  @click="addContractPartyRow(index)"
                  v-if="index === contractPartyList.length - 1"
                  :disabled="hasContractPartyErrors"
                />
              </a-tooltip>
              <a-tooltip title="删除此行" v-if="index != 0">
                <!-- {{ index == contractPartyList.length - 1 }} -->
                <a-button
                  style="background-color: #d9d9d9"
                  type="default"
                  shape="circle"
                  icon="minus"
                  size="small"
                  @click="removeContractPartyRow(index)"
                  v-if="index === contractPartyList.length - 1"
                />
              </a-tooltip>
            </div>
          </template>

          <!-- 表头添加必填标识 -->
          <template slot="institutionNameTitle" slot-scope="title">
            <span class="required-label">*</span>{{ title }}
          </template>
        </a-table>

        <a-divider orientation="left">设备清单</a-divider>
        <a-table
          :columns="contractEquipmentColumns"
          :dataSource="contractEquipmentList"
          :pagination="false"
          bordered
          size="middle"
          rowKey="key"
        >
          <!-- 自定义单元格渲染 - 可编辑单元格 v-for="(row, index) in data" -->
          <template
            v-for="col in editableContractEquipmentColumns"
            :slot="col.dataIndex"
            slot-scope="text, record, index"
          >
            <div :key="col.dataIndex" class="editable-cell">
              <span
                v-if="
                  col.dataIndex == 'equipmentName' ||
                  col.dataIndex == 'brand' ||
                  col.dataIndex == 'model' ||
                  col.dataIndex == 'manufacturer' ||
                  col.dataIndex == 'equipmentTotalAmount'
                "
                >{{ text }}
              </span>
              <span
                v-else-if="
                  col.dataIndex == 'warrantyPeriod' ||
                  col.dataIndex == 'deviceNumber'
                "
              >
                <a-input
                  type="number"
                  v-if="record.equipmentName != null"
                  v-model="record[col.dataIndex]"
                  :min="0"
                  @blur="validateContractEquipmentField(record, col.dataIndex)"
                  @change="
                    contractEquipmentChange(record, col.dataIndex, index)
                  "
                  :class="{
                    'error-field':
                      record.errors && record.errors[col.dataIndex],
                  }"
                />
                <text v-else>{{ text }}</text>
              </span>
              <span v-else>
                <a-input
                  v-if="record.equipmentName != null"
                  v-model="record[col.dataIndex]"
                  @blur="validateContractEquipmentField(record, col.dataIndex)"
                  :class="{
                    'error-field':
                      record.errors && record.errors[col.dataIndex],
                  }"
                  @change="
                    contractEquipmentChange(record, col.dataIndex, index)
                  "
                />
                <text v-else>{{ text }}</text>
              </span>

              <div
                class="error-message"
                v-if="record.errors && record.errors[col.dataIndex]"
              >
                {{ record.errors[col.dataIndex] }}
              </div>
            </div>
          </template>

          <!-- 操作列 - 添加/删除行按钮 -->
          <template slot="action" slot-scope="text, record, index">
            <a
              style="font-size: 12px"
              @click="editContractEquipmentRow(record, index)"
              v-wx-role="6030602"
            >
              <a-icon type="edit" />编辑</a
            >
            <a-divider type="vertical" />
            <a
              @click="removeContractEquipmentRow(index)"
              style="color: red; font-size: 12px"
            >
              <a-icon type="delete" />移除</a
            >
          </template>

          <!-- 表头添加必填标识 -->
          <template slot="warrantyPeriodTitle" slot-scope="title">
            <span class="required-label">*</span>{{ title }}
          </template>
          <template slot="deviceNumberTitle" slot-scope="title">
            <span class="required-label">*</span>{{ title }}
          </template>
          <template slot="equipmentUnitPriceTitle" slot-scope="title">
            <span class="required-label">*</span>{{ title }}
          </template>
        </a-table>

        <div class="table-footer">
          <a-button
            type="primary"
            icon="plus"
            @click="addContractEquipmentRow(contractEquipmentList.length - 1)"
            :disabled="hasContractEquipmentErrors"
          >
            添加设备
          </a-button>
        </div>
        <div class="table-footerMoney">
          <span style="float: left"> 成交总价（元）</span>
          <span
            >大写：{{
              this.amountToChinese(
                this.contractEquipmentTotalSum == null
                  ? '0.00'
                  : this.contractEquipmentTotalSum
              ) || '零元'
            }}</span
          >
          <span style="float: right"
            >小写：{{ this.contractEquipmentTotalSum || 0.0 }}</span
          >
        </div>

        <a-divider orientation="left">资金来源</a-divider>
        <a-table
          :columns="contractFundsSourceColumns"
          :dataSource="contractFundsSourceList"
          :pagination="false"
          bordered
          size="middle"
          rowKey="key"
        >
          <!-- 自定义单元格渲染 - 可编辑单元格 v-for="(row, index) in data" -->
          <template
            v-for="col in editableContractFundsSourceColumns"
            :slot="col.dataIndex"
            slot-scope="text, record, index"
          >
            <!-- fundsSource -->
            <div :key="col.dataIndex" class="editable-cell">
              <span v-if="col.dataIndex == 'fundsSource'">
                <a-select
                  v-model="record[col.dataIndex]"
                  placeholder="请选择资金来源"
                  @blur="
                    validateContractFundsSourceField(record, col.dataIndex)
                  "
                  :class="{
                    'error-field':
                      record.errors && record.errors[col.dataIndex],
                  }"
                >
                  <a-select-option
                    v-for="item in fundsSourceList"
                    :key="item.itemValue"
                    :value="item.itemValue"
                  >
                    {{ item.itemText }}</a-select-option
                  >
                </a-select>
              </span>
              <span v-else-if="col.dataIndex == 'amount'">{{ text }}</span>
              <span v-else>
                <a-input
                  type="number"
                  v-model="record[col.dataIndex]"
                  :min="0"
                  @blur="
                    validateContractFundsSourceField(record, col.dataIndex)
                  "
                  @change="
                    contractFundsSourceChange(record, col.dataIndex, index)
                  "
                  :class="{
                    'error-field':
                      record.errors && record.errors[col.dataIndex],
                  }"
                />
              </span>

              <div
                class="error-message"
                v-if="record.errors && record.errors[col.dataIndex]"
              >
                {{ record.errors[col.dataIndex] }}
              </div>
            </div>
          </template>

          <!-- 操作列 - 添加/删除行按钮 -->
          <template slot="action" slot-scope="text, record, index">
            <div class="action-buttons">
              <a-tooltip title="添加一行">
                <a-button
                  type="primary"
                  shape="circle"
                  icon="plus"
                  size="small"
                  @click="addContractFundsSourceRow(index)"
                  v-if="index === contractFundsSourceList.length - 1"
                  :disabled="hasContractFundsSourceErrors"
                />
              </a-tooltip>
              <a-tooltip title="删除此行" v-if="index != 0">
                <!-- {{ index == contractPartyList.length - 1 }} -->
                <a-button
                  style="background-color: #d9d9d9"
                  type="default"
                  shape="circle"
                  icon="minus"
                  size="small"
                  @click="removeContractFundsSourceRow(index)"
                  v-if="contractFundsSourceList.length > 1"
                />
              </a-tooltip>
            </div>
          </template>

          <!-- 表头添加必填标识 -->
          <template slot="fundsSourceTitle" slot-scope="title">
            <span class="required-label">*</span>{{ title }}
          </template>
          <template slot="sourceRatioTitle" slot-scope="title">
            <span class="required-label">*</span>{{ title }}
          </template>
          <template slot="amountTitle" slot-scope="title">
            <span class="required-label">*</span>{{ title }}
          </template>
        </a-table>
        <div class="table-footerMoney">
          <span style="float: left"> 成交总价（元）</span>
          <span
            >大写：{{
              this.amountToChinese(this.contractFundsSourceTotalSum) || '零元'
            }}</span
          >
          <span style="float: right"
            >小写：{{ this.contractFundsSourceTotalSum || 0.0 }}</span
          >
        </div>
        <a-divider orientation="left">质保期</a-divider>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="质保日期" prop="warrantyPeriod">
              <a-range-picker
                v-model="warrantyPeriod"
                @change="warrantyPeriodDateChange"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">随机资料</a-divider>
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="随机资料包括"
              prop="information"
              :rules="$valid.required"
              :maxLength="50"
            >
              <a-input
                v-model="formInfo.information"
                placeholder="请输入随机资料"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">器械交付日期</a-divider>
        <div class="contract-container">
          <!-- 乙方在合同生效的{deliveryDateEquipmentDay}天内向甲方交付上述器械。-->
          <div class="clause-item">
            <span class="clause-text">
              乙方在合同生效的
              <a-input
                class="underline-input"
                v-model="formInfo.deliveryDateEquipmentDay"
                placeholder=" "
              />
              天内向甲方交付上述器械。
            </span>
          </div>
        </div>

        <a-divider orientation="left">器械运输、安装和验收</a-divider>
        <div class="contract-container">
          <!-- 条款1 -->
          <!-- （1）乙方还应在发货前{clause1}个工作日通知甲方器械的运输信息以及到货时间。-->
          <div class="clause-item">
            <span class="clause-text">
              （1）乙方还应在发货前
              <a-input
                class="underline-input"
                v-model="clause1"
                placeholder=" "
              />
              个工作日通知甲方器械的运输信息以及到货时间。
            </span>
          </div>

          <!-- 条款2 -->
          <!-- （2）器械到货后，乙方应在接到甲方通知后{clause2}天内安装调试完成。 -->
          <div class="clause-item">
            <span class="clause-text">
              （2）器械到货后，乙方应在接到甲方通知后
              <a-input
                class="underline-input"
                v-model="clause2"
                placeholder=" "
              />
              天内安装调试完成。
            </span>
          </div>

          <!-- 条款3 -->
          <!-- 
            （3）甲乙双方对器械进行开箱清点检查验收，如果发现数量不足或有质量、技术等问题，乙方应在{clause3}
           天内，按照甲方的要求，采取补足、更换或退货等处理措施。
          -->
          <div class="clause-item">
            <span class="clause-text">
              （3）甲乙双方对器械进行开箱清点检查验收，如果发现数量不足或有质量、技术等问题，乙方应在
              <a-input
                class="underline-input"
                v-model="clause3"
                placeholder=" "
              />
              天内，按照甲方的要求，采取补足、更换或退货等处理措施。
            </span>
          </div>
        </div>
        <a-divider orientation="left">交付条件</a-divider>
        <div class="contract-container">
          <!-- 条款1 -->

          <div class="clause-item">
            <span class="clause-text">
              甲方在收到乙方发票并确认无误后,应在
              <a-input
                class="underline-input"
                v-model="formInfo.withinFewMonth"
                placeholder=" "
              />
              个月内支付货款，共计
              <a-input
                class="underline-input"
                v-model="formInfo.contractAmount"
                placeholder=" "
                @change="contractAmountChange(formInfo.contractAmount)"
              />
              元，大写
              {{ clause14 || '' }}
            </span>
          </div>
        </div>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="付款方式" prop="payMonth">
              <a-select
                :size="'default'"
                style="min-width: 100px"
                :showArrow="true"
                v-model="formInfo.payMonth"
                placeholder="请选择付款方式"
              >
                <a-select-option
                  v-for="item in payMonthList"
                  :key="item.itemValue"
                  :value="item.itemValue"
                >
                  {{ item.itemText }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <!-- 付款期数 -->
        <a-table
          :columns="contractPaymentTermColumns"
          :dataSource="contractPaymentTermList"
          :pagination="false"
          bordered
          size="middle"
          rowKey="key"
        >
          <!-- 自定义单元格渲染 - 可编辑单元格 v-for="(row, index) in data" -->
          <template
            v-for="col in editableContractPaymentTermColumns"
            :slot="col.dataIndex"
            slot-scope="text, record, index"
          >
            <!-- fundsSource -->
            <div :key="col.dataIndex" class="editable-cell">
              <span v-if="col.dataIndex == 'payNumber'">
                {{ text == '1' ? '首期' : '第' + text + '期' }}
              </span>
              <span v-else-if="col.dataIndex == 'payMoney'">
                {{ text }}
              </span>
              <a-input
                v-else
                type="number"
                v-model="record[col.dataIndex]"
                :min="0"
                @blur="validateContractPaymentTermField(record, col.dataIndex)"
                @change="
                  contractPaymentTermChange(record, col.dataIndex, index)
                "
                :class="{
                  'error-field': record.errors && record.errors[col.dataIndex],
                }"
              />

              <div
                class="error-message"
                v-if="record.errors && record.errors[col.dataIndex]"
              >
                {{ record.errors[col.dataIndex] }}
              </div>
            </div>
          </template>

          <!-- 操作列 - 添加/删除行按钮 -->
          <template slot="action" slot-scope="text, record, index">
            <div class="action-buttons">
              <a-tooltip title="添加一行">
                <a-button
                  type="primary"
                  shape="circle"
                  icon="plus"
                  size="small"
                  @click="addContractPaymentTermRow(index)"
                  v-if="index === contractPaymentTermList.length - 1"
                  :disabled="hasContractPaymentTermErrors"
                />
              </a-tooltip>
              <a-tooltip title="删除此行" v-if="index != 0">
                <a-button
                  style="background-color: #d9d9d9"
                  type="default"
                  shape="circle"
                  icon="minus"
                  size="small"
                  @click="removeContractPaymentTermRow(index)"
                  v-if="
                    contractPaymentTermList.length > 1 &&
                    index === contractPaymentTermList.length - 1
                  "
                />
              </a-tooltip>
            </div>
          </template>
        </a-table>
        <div class="table-footerMoney">
          <span style="float: left"> 总计（元）</span>
          <span>{{ this.contractPaymentTermTotalSum || 0.0 }}</span>
        </div>
        <a-form-model-item
          style="margin-top: 30px; font-size: 15px; font-weight: 500"
          >乙方收款账户信息如下:</a-form-model-item
        >
        <a-row style="margin-top: -20px">
          <a-col :span="12">
            <a-form-model-item label="开户名" prop="accountName">
              <a-input
                v-model="formInfo.accountName"
                placeholder="请输入开户名"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="纳税人识别号" prop="taxpayerNumber">
              <a-input
                v-model="formInfo.taxpayerNumber"
                placeholder="请输入纳税人识别号"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="开户银行" prop="bank">
              <a-input v-model="formInfo.bank" placeholder="请输入开户银行" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="银行卡号" prop="bankCard">
              <a-input
                v-model="formInfo.bankCard"
                placeholder="请输入银行卡号"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-divider orientation="left">质量保证及售后服务</a-divider>
        <div class="contract-container">
          <!-- 乙方应在保证所供器械实再{clause4} 后产生的全新的、未使用过的，并符合国家有关标准、行业有关标准、制造厂标准及合同技术标准要求。-->
          <div class="clause-item">
            <span class="clause-text">
              乙方应在保证所供器械实再
              <a-date-picker
                style="width: 15%"
                v-model="clause4"
                inputReadOnly
                type="date"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                placeholder=""
              />
              <!-- <a-input v-model="clause4" placeholder=" " /> -->
              后产生的全新的、未使用过的，并符合国家有关标准、行业有关标准、制造厂标准及合同技术标准要求。
            </span>
          </div>
        </div>
        <a-form-model-item
          style="
            margin-top: 0px;
            margin-left: 22px;
            font-size: 15px;
            font-weight: 500;
          "
          >质保期服务条件</a-form-model-item
        >
        <div class="contract-container" style="margin-top: -36px">
          <!-- 条款1 -->
          <!-- 
            （1）甲方进行故障保修后,乙方应在{clause5}{clause6} 内接修，
            接修后应在{clause7}{clause8}内到达现场。
           -->
          <div class="clause-item">
            <span class="clause-text">
              （1）甲方进行故障保修后,乙方应在
              <a-input
                class="underline-input"
                v-model="clause5"
                placeholder=" "
              />
              <a-select
                v-model="clause6"
                class="unit-select"
                style="border: none"
              >
                <a-select-option value="minutes">分钟</a-select-option>
                <a-select-option value="hours">小时</a-select-option>
              </a-select>
              内接修，接修后应在
              <a-input
                class="underline-input"
                v-model="clause7"
                placeholder=" "
              />
              <a-select
                v-model="clause8"
                class="unit-select"
                style="border: none"
              >
                <a-select-option value="minutes">分钟</a-select-option>
                <a-select-option value="hours">小时</a-select-option>
              </a-select>
              内到达现场。
            </span>
          </div>

          <!-- 条款2 -->
          <!-- 
            （2）为保障甲方设备的正常运行，以防应每年做预防性维护{clause9}次、检测{clause10} 次，
            每次维护后，乙方提供设备运行状况报告给甲方备案。
           
          -->
          <div class="clause-item">
            <span class="clause-text">
              （2）为保障甲方设备的正常运行，以防应每年做预防性维护
              <a-input
                class="underline-input"
                v-model="clause9"
                placeholder=" "
              />
              次、检测
              <a-input
                class="underline-input"
                v-model="clause10"
                placeholder=" "
              />
              次，每次维护后，乙方提供设备运行状况报告给甲方备案。
            </span>
          </div>

          <!-- 条款3 -->
          <!--  （3）保修的设备在一年内开机率保证在{clause11} %以上，每年设备累计停机时长不超过{clause12}个工作日。 -->
          <div class="clause-item">
            <span class="clause-text">
              （3）保修的设备在一年内开机率保证在
              <a-input
                class="underline-input"
                v-model="clause11"
                placeholder=" "
              />
              %以上，每年设备累计停机时长不超过
              <a-input
                class="underline-input"
                v-model="clause12"
                placeholder=" "
              />
              个工作日。
            </span>
          </div>
          <!-- 条款4 -->
          <!-- 
            （4）在保修期内，涉及到不在保修范围内的器件，如需更换，乙方以市场价的{clause13}%优惠提供。
           -->
          <div class="clause-item">
            <span class="clause-text">
              （4）在保修期内，涉及到不在保修范围内的器件，如需更换，乙方以市场价的

              <a-input
                class="underline-input"
                v-model="clause13"
                placeholder=" "
              />
              %优惠提供。
            </span>
          </div>
        </div>
        <a-row>
          <a-col :span="24">
            <a-form-model-item
              :labelCol="$global.labelTextAreaCol"
              :wrapperCol="$global.wrapperTextAreaCol"
              label="服务备注"
            >
              <a-input v-model="formInfo.serveRemark" type="textarea" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">其他关键条款</a-divider>
        <a-table
          :columns="contractOtherColumns"
          :dataSource="contractOtherList"
          :pagination="false"
          bordered
          size="middle"
          rowKey="key"
        >
          <!-- 自定义单元格渲染 - 可编辑单元格 v-for="(row, index) in data" -->
          <template
            v-for="col in editableContractOtherColumns"
            :slot="col.dataIndex"
            slot-scope="text, record, index"
          >
            <!-- fundsSource -->
            <div :key="col.dataIndex" class="editable-cell">
              <span v-if="col.dataIndex == 'number'">
                {{ text }}
              </span>
              <a-input
                v-else
                type="textarea"
                v-model="record[col.dataIndex]"
                row="4"
              />

              <div
                class="error-message"
                v-if="record.errors && record.errors[col.dataIndex]"
              >
                {{ record.errors[col.dataIndex] }}
              </div>
            </div>
          </template>

          <!-- 操作列 - 添加/删除行按钮 -->
          <template slot="action" slot-scope="text, record, index">
            <div class="action-buttons">
              <a-tooltip title="添加一行">
                <a-button
                  type="primary"
                  shape="circle"
                  icon="plus"
                  size="small"
                  @click="addContractOtherRow(index)"
                  v-if="index === contractOtherList.length - 1"
                  :disabled="hasContractOtherErrors"
                />
              </a-tooltip>
              <a-tooltip title="删除此行" v-if="index != 0">
                <a-button
                  style="background-color: #d9d9d9"
                  type="default"
                  shape="circle"
                  icon="minus"
                  size="small"
                  @click="removeContractOtherRow(index)"
                  v-if="
                    contractOtherList.length > 1 &&
                    index === contractOtherList.length - 1
                  "
                />
              </a-tooltip>
            </div>
          </template>
        </a-table>
        <a-divider orientation="left">相关文件</a-divider>
        <a-row>
          <a-col :span="12">
            <a-form-model-item
              label="采购申请"
              prop="purchaseRequisitionFile"
              :maxLength="50"
            >
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.purchaseRequisitionFile"
                bizPath="annexUrl"
              >
              </w-file-upload>
              <!-- <a-input
                v-model="formInfo.purchaseRequisitionFile"
                placeholder="请输入采购申请"
              /> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="购置论证"
              prop="purchaseJustificationFile"
            >
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.purchaseJustificationFile"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="招标文件" prop="bidDocumentFile">
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.bidDocumentFile"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="投标文件" prop="biddingDocumentFile">
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.biddingDocumentFile"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="中标文件" prop="bidWinningDocumentFile">
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.bidWinningDocumentFile"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="合同原件" prop="contractOriginal">
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.contractOriginal"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="配置清单" prop="configurationListFile">
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.configurationListFile"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="响应文件" prop="responseFile">
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.responseFile"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="其他附件" prop="otherAccessoryFile">
              <w-file-upload
                class="avatar-uploader"
                text="上传"
                :pdfOnly="true"
                :multipleFlag="true"
                v-model="formInfo.otherAccessoryFile"
                bizPath="annexUrl"
              >
              </w-file-upload>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row style="margin-left: -50px">
          <a-col :span="24">
            <a-form-model-item
              :labelCol="$global.labelTextAreaCol"
              :wrapperCol="$global.wrapperTextAreaCol"
              label="备注"
            >
              <a-input v-model="formInfo.remarks" type="textarea" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <div style="height: 60px"></div>
      </a-form-model>
    </a-spin>

    <div
      v-if="this.isDisabled != '0'"
      style="
        display: flex;
        justify-content: flex-end; /* 将内容推到右侧 */
        align-items: flex-end; /* 将内容推到下方 */
        height: 100vh; /* 容器高度设为视口高度，确保它在屏幕底部 */
      "
    >
      <a-button
        v-if="this.isDisabled == '1' || this.isDisabled == '2'"
        @confirm="handleCancel"
        style="margin-right: 0.8rem"
        >取消</a-button
      >
      <a-button
        style="margin-right: 0.8rem"
        @click="handleSubmit(1)"
        type="default"
        :loading="confirmLoading"
        >存为草稿</a-button
      >
      <a-button
        style="margin-right: 0.8rem"
        @click="handleSubmit(0)"
        type="primary"
        :loading="confirmLoading"
        >确认建档</a-button
      >
    </div>
    <dev-contract-equipment
      ref="contractEquipmentEditRef"
      @ok="contractEquipmentEditOk"
      @close="contractEquipmentClose"
    ></dev-contract-equipment>
  </div>
</template>

<script>
import moment from 'moment'
import { getAction, postAction } from '@/api/manage'
import WFileUpload from '@/components/WxFileUpload/WFileUpload'
import DevContractEquipment from './DevContractEquipment'
import { getByDictCodeList } from '@/api/api'
export default {
  name: 'DevContractSave',
  components: { WFileUpload, DevContractEquipment },
  data() {
    return {
      contractProcurementMethodList: [],
      administrativeDeptList: [],
      payMonthList: [],
      procurementFormList: [],
      approvedByList: [],
      equipmentAmountCapitalLetters: '',
      equipmentAmountCapitalLowercase: '0.00',
      //START 器械交付日期条款
      clause1: '',
      clause2: '',
      clause3: '',
      //END 器械交付日期条款
      //START质量保证及售后服务
      clause4: '',
      clause5: '',
      clause6: 'hours',
      clause7: '',
      clause8: 'hours',
      clause9: '',
      clause10: '',
      clause11: '',
      clause12: '',
      clause13: '',
      //END质量保证及售后服务
      clause14: '',
      visible: false,
      confirmLoading: false,
      contractClassification: '0',
      formInfo: {
        id: undefined,
        createTime: undefined,
        contractClassification: undefined,
        contractType: undefined,
        contractName: undefined,
        contractNumber: undefined,
        contractProcurementMethodId: undefined,
        signingDate: undefined,
        associatedProject: undefined,
        associatedBudget: undefined,
        salespersonName: undefined,
        administrativeDept: undefined,
        procurementForm: undefined,
        approvedBy: undefined,
        warrantyStartPeriod: undefined,
        warrantyEndPeriod: undefined,
        information: undefined,
        deliveryDateEquipmentDay: undefined,
        transportationInstallatio: undefined,
        withinFewMonth: undefined,
        contractAmount: undefined,
        payMonth: undefined,
        accountName: undefined,
        taxpayerNumber: undefined,
        bank: undefined,
        bankCard: undefined,
        qualityAssuranceAfterService: undefined,
        serveRemark: undefined,
        otherKeyTerm: undefined,
        purchaseRequisitionFile: undefined,
        purchaseJustificationFile: undefined,
        bidDocumentFile: undefined,
        biddingDocumentFile: undefined,
        bidWinningDocumentFile: undefined,
        contractOriginal: undefined,
        configurationListFile: undefined,
        responseFile: undefined,
        otherAccessoryFile: undefined,
        remarks: undefined,
        wx: '',
      },
      isDisabled: '',
      contractPartyListIndex: 0,
      contractPartyColumns: [
        {
          title: '签约方',
          dataIndex: 'partyName',
          width: 80,
          scopedSlots: {
            customRender: 'partyName',
          },
        },
        {
          title: '机构名称',
          dataIndex: 'institutionName',
          width: 120,
          scopedSlots: {
            customRender: 'institutionName',
            title: 'institutionNameTitle',
          },
        },
        {
          title: '地址',
          dataIndex: 'address',
          scopedSlots: {
            customRender: 'address',
          },
        },
        {
          title: '联系人',
          dataIndex: 'contactName',
          scopedSlots: { customRender: 'contactName' },
        },
        {
          title: '联系电话',
          dataIndex: 'contactPhone',
          scopedSlots: { customRender: 'contactPhone' },
        },
        {
          title: 'email',
          dataIndex: 'email',
          scopedSlots: { customRender: 'email' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '10%',
          scopedSlots: { customRender: 'action' },
        },
      ],

      contractPartyList: [],
      partyNameList: [
        '甲方',
        '乙方',
        '丙方',
        '丁方',
        '戊方',
        '己方',
        '庚方',
        '辛方',
        '壬方',
        '癸方',
      ],
      contractEquipmentColumns: [
        {
          title: '设备名称',
          dataIndex: 'equipmentName',
          width: 80,
          scopedSlots: {
            customRender: 'equipmentName',
            title: 'equipmentNameTitle',
          },
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          width: 120,
          scopedSlots: {
            customRender: 'brand',
          },
        },
        {
          title: '型号',
          dataIndex: 'model',
          scopedSlots: {
            customRender: 'model',
          },
        },
        {
          title: '生产厂商',
          dataIndex: 'manufacturer',
          scopedSlots: { customRender: 'manufacturer' },
        },
        {
          title: '质保期',
          dataIndex: 'warrantyPeriod',
          scopedSlots: {
            customRender: 'warrantyPeriod',
            title: 'warrantyPeriodTitle',
          },
        },
        {
          title: '数量',
          dataIndex: 'deviceNumber',
          scopedSlots: {
            customRender: 'deviceNumber',
            title: 'deviceNumberTitle',
          },
        },
        {
          title: '单价',
          dataIndex: 'equipmentUnitPrice',
          scopedSlots: {
            customRender: 'equipmentUnitPrice',
            title: 'equipmentUnitPriceTitle',
          },
        },
        {
          title: '总金额',
          dataIndex: 'equipmentTotalAmount',
          scopedSlots: {
            customRender: 'equipmentTotalAmount',
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '13%',
          scopedSlots: { customRender: 'action' },
        },
      ],
      contractEquipmentList: [],
      contractFundsSourceColumns: [
        {
          title: '资金来源',
          dataIndex: 'fundsSource',
          width: 300,
          scopedSlots: {
            customRender: 'fundsSource',
            title: 'fundsSourceTitle',
          },
        },
        {
          title: '来源比例（%）',
          dataIndex: 'sourceRatio',
          scopedSlots: {
            customRender: 'sourceRatio',
            title: 'sourceRatioTitle',
          },
        },
        {
          title: '金额（元）',
          dataIndex: 'amount',
          scopedSlots: {
            customRender: 'amount',
            title: 'amount',
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '10%',
          scopedSlots: { customRender: 'action' },
        },
      ],
      contractFundsSourceList: [
        {
          key: Date.now().toString(),
          contractId: undefined,
          fundsSource: undefined,
          sourceRatio: 0.0,
          amount: 0.0,
          errors: {},
        },
      ],
      contractPaymentTermColumns: [
        {
          title: '付款期数',
          dataIndex: 'payNumber',
          width: 300,
          scopedSlots: {
            customRender: 'payNumber',
          },
        },
        {
          title: '付款比例（%）',
          dataIndex: 'payRatio',
          scopedSlots: {
            customRender: 'payRatio',
          },
        },
        {
          title: '付款金额（元）',
          dataIndex: 'payMoney',
          scopedSlots: {
            customRender: 'payMoney',
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '10%',
          scopedSlots: { customRender: 'action' },
        },
      ],
      contractPaymentTermList: [
        {
          key: Date.now().toString(),
          contractId: undefined,
          payNumber: '1',
          payRatio: 0,
          payMoney: 0.0,
          errors: {},
        },
      ],

      contractOtherColumns: [
        {
          title: '条款项',
          dataIndex: 'number',
          width: 100,
          scopedSlots: {
            customRender: 'number',
          },
        },
        {
          title: '条款内容',
          dataIndex: 'otherKeyTerm',
          scopedSlots: {
            customRender: 'otherKeyTerm',
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '10%',
          scopedSlots: { customRender: 'action' },
        },
      ],
      contractOtherList: [
        {
          key: Date.now().toString(),
          number: '1',
          otherKeyTerm: undefined,
          errors: {},
        },
      ],
      warrantyPeriod: [],
      url: {
        saveInfo: '/system/devContract/save',
        getInfo: '/system/devContract/info',
        getSupplierList: '/system/devSupplier/getList',
      },
      supplierList: [],
      fundsSourceList: [],
    }
  },
  computed: {
    contractPaymentTermTotalSum() {
      return this.contractPaymentTermList.reduce(
        (sum, item) => parseFloat(sum) + parseFloat(item.payMoney),
        0
      )
    },

    contractEquipmentTotalSum() {
      return this.contractEquipmentList.reduce(
        (sum, item) => parseFloat(sum) + parseFloat(item.equipmentTotalAmount),
        0
      )
    },
    contractFundsSourceTotalSum() {
      return this.contractFundsSourceList.reduce(
        (sum, item) => parseFloat(sum) + parseFloat(item.amount),
        0
      )
    },

    editableContractOtherColumns() {
      return this.contractOtherColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
    // 检查是否有错误
    hasContractOtherErrors() {
      return this.contractOtherList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },

    editableContractPaymentTermColumns() {
      return this.contractPaymentTermColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
    // 检查是否有错误
    hasContractPaymentTermErrors() {
      return this.contractPaymentTermList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },

    editableContractFundsSourceColumns() {
      return this.contractFundsSourceColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },

    // 检查是否有错误
    hasContractFundsSourceErrors() {
      return this.contractFundsSourceList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },

    editableContractEquipmentColumns() {
      return this.contractEquipmentColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
    // 检查是否有错误
    hasContractEquipmentErrors() {
      return this.contractEquipmentList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },

    editableContractPartyColumns() {
      return this.contractPartyColumns.filter(
        (col) => col.dataIndex !== 'action'
      )
    },
    // 检查是否有错误
    hasContractPartyErrors() {
      return this.contractPartyList.some(
        (row) => row.errors && Object.keys(row.errors).length > 0
      )
    },
  },
  created() {
    this.getSupplierList()
    this.getDictCodeList()
  },
  methods: {
    getDictCodeList() {
      //采购方式
      getByDictCodeList({
        dictCode: 'contractProcurementMethod',
      }).then((res) => {
        this.contractProcurementMethodList = res.result.data
      })
      //管理部门
      getByDictCodeList({
        dictCode: 'administrativeDept',
      }).then((res) => {
        this.administrativeDeptList = res.result.data
      })
      //资金来源
      getByDictCodeList({
        dictCode: 'fundsSource',
      }).then((res) => {
        this.fundsSourceList = res.result.data
      })
      //采购组织形式
      getByDictCodeList({
        dictCode: 'procurementForm',
      }).then((res) => {
        this.procurementFormList = res.result.data
      })
      //配置批准单位
      getByDictCodeList({
        dictCode: 'approved_by',
      }).then((res) => {
        this.approvedByList = res.result.data
      })

      //付款方式
      getByDictCodeList({
        dictCode: 'contract_pay_month',
      }).then((res) => {
        this.payMonthList = res.result.data
      })
    },
    //合同金额
    contractAmountChange(contractAmount) {
      if (contractAmount == null) {
        contractAmount = 0.0
      }
      this.clause14 = this.amountToChinese(contractAmount)
    },
    //金额大写
    amountToChinese(amount) {
      const fraction = ['角', '分']
      const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']
      const unit = [
        ['元', '万', '亿'],
        ['', '拾', '百', '千'],
      ]
      let num = Math.abs(amount)
      let s = ''
      fraction.forEach((item, index) => {
        s += (
          digit[Math.floor(num * 10 * Math.pow(10, index)) % 10] + item
        ).replace(/零./, '')
      })
      s = s || '整'
      num = Math.floor(num)
      for (let i = 0; i < unit[0].length && num > 0; i++) {
        let p = ''
        for (let j = 0; j < unit[1].length && num > 0; j++) {
          p = digit[num % 10] + unit[1][j] + p
          num = Math.floor(num / 10)
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s
      }
      return s
        .replace(/(零.)*零元/, '元')
        .replace(/(零.)+/g, '零')
        .replace(/^整$/, '零元整')
    },

    //计算设备清单总金额
    contractEquipmentChange(record, column, index) {
      if (record.deviceNumber && record.equipmentUnitPrice) {
        record.equipmentTotalAmount =
          record.deviceNumber * record.equipmentUnitPrice
      } else {
        record.equipmentTotalAmount = 0.0
      }
    },

    warrantyPeriodDateChange(value, dateString) {
      this.formInfo.warrantyStartPeriod = dateString[0]
      this.formInfo.warrantyEndPeriod = dateString[1]
    },

    // START其他条款
    contractOtherChange(record, column, index) {},
    // 添加新行
    addContractOtherRow(index) {
      if (this.hasContractOtherErrors) return
      var indexOf = index + 1
      console.log('indexOf+1>>', indexOf + 1)
      this.contractOtherList.splice(indexOf, 0, {
        key: Date.now().toString(),
        number: indexOf + 1,
        otherKeyTerm: '',
        errors: {},
      })
    },

    // 删除行
    removeContractOtherRow(index) {
      this.contractOtherList.splice(index, 1)
    },

    // 验证字段
    validateContractOtherField(record, field) {
      // 清除旧错误
      if (record.errors && record.errors[field]) {
        this.$delete(record.errors, field)
      }

      // 必填校验规则
      const requiredFields = ['fundsSource', 'sourceRatio', 'amount']
      if (requiredFields.includes(field) && !record[field]) {
        this.$set(
          record.errors,
          field,
          `${this.getContractOtherFieldTitle(field)}不能为空`
        )
      }
    },

    // 获取字段标题
    getContractOtherFieldTitle(field) {
      const column = this.contractOtherColumns.find(
        (col) => col.dataIndex === field
      )
      return column ? column.title : field
    },

    // END其他条款

    // START分期期数
    contractPaymentTermChange(record, column, index) {
      if (record.payRatio) {
        if (!this.formInfo.contractAmount) {
          this.$message.error('请输入付款条件总金额!')
          record.payRatio = 0
        }
        //付款比例转换为小数
        var payRatio = parseFloat(record.payRatio) / parseFloat(100)
        record.payMoney =
          parseFloat(this.formInfo.contractAmount) * parseFloat(payRatio)
      }
      if (record.payMoney == null) {
        record.payMoney = 0.0
      }
    },
    // 添加新行
    addContractPaymentTermRow(index) {
      if (this.hasContractPaymentTermErrors) return
      var indexOf = index + 1
      console.log('indexOf+1>>', indexOf + 1)
      this.contractPaymentTermList.splice(indexOf, 0, {
        key: Date.now().toString(),
        contractId: undefined,
        payNumber: indexOf + 1,
        payRatio: 0,
        payMoney: 0.0,
        errors: {},
      })
    },

    // 删除行
    removeContractPaymentTermRow(index) {
      this.contractPaymentTermList.splice(index, 1)
    },

    // 验证字段
    validateContractPaymentTermField(record, field) {
      // 清除旧错误
      if (record.errors && record.errors[field]) {
        this.$delete(record.errors, field)
      }

      // 必填校验规则
      const requiredFields = ['fundsSource', 'sourceRatio', 'amount']
      if (requiredFields.includes(field) && !record[field]) {
        this.$set(
          record.errors,
          field,
          `${this.getContractPaymentTermFieldTitle(field)}不能为空`
        )
      }
    },

    // 获取字段标题
    getContractPaymentTermFieldTitle(field) {
      const column = this.contractPaymentTermColumns.find(
        (col) => col.dataIndex === field
      )
      return column ? column.title : field
    },

    // END分期期数

    // START资金来源
    contractFundsSourceChange(record, column, index) {
      if (record.sourceRatio) {
        record.amount = (
          (record.sourceRatio / 100) *
          this.contractEquipmentTotalSum
        ).toFixed(2)
      } else {
        record.amount = 0.0
      }
      if (this.contractFundsSourceTotalSum > this.contractEquipmentTotalSum) {
        record.amount = 0.0
        this.$message.error('分项资金总值不等于成交总价!')
      }
    },
    // 添加新行
    addContractFundsSourceRow(index) {
      if (this.hasContractFundsSourceErrors) return
      var indexOf = index + 1

      this.contractFundsSourceList.splice(indexOf, 0, {
        key: Date.now().toString(),
        contractId: undefined,
        fundsSource: undefined,
        sourceRatio: 0.0,
        amount: 0.0,
        errors: {},
      })
    },

    // 删除行
    removeContractFundsSourceRow(index) {
      this.contractFundsSourceList.splice(index, 1)
    },

    // 验证字段
    validateContractFundsSourceField(record, field) {
      // 清除旧错误
      if (record.errors && record.errors[field]) {
        this.$delete(record.errors, field)
      }

      // 必填校验规则
      const requiredFields = ['fundsSource', 'sourceRatio', 'amount']
      if (requiredFields.includes(field) && !record[field]) {
        this.$set(
          record.errors,
          field,
          `${this.getContractFundsSourceFieldTitle(field)}不能为空`
        )
      }
    },

    // 获取字段标题
    getContractFundsSourceFieldTitle(field) {
      const column = this.contractFundsSourceColumns.find(
        (col) => col.dataIndex === field
      )
      return column ? column.title : field
    },

    // END资金来源

    // START设备清单
    // 添加新行
    addContractEquipmentRow(index) {
      if (this.hasContractEquipmentErrors) return
      var indexOf = index + 1

      var record = {
        key: Date.now().toString(),
        contractId: undefined,
        equipmentName: undefined,
        genericName: undefined,
        brand: undefined,
        model: undefined,
        manufacturer: undefined,
        serviceLife: undefined,
        differentCountrie: undefined,
        isDomesticallyProduced: undefined,
        productAppearanceImage: undefined,
        isTrader: undefined,
        certificateAuthorizationFile: undefined,
        isMedicalDevice: false,
        medicalDeviceRegistrationNumber: undefined,
        medicalDeviceRegistrationFile: undefined,
        configurationParameter: undefined,
        dailyInspectionTemplateFile: undefined,
        inspectionTemplateFile: undefined,
        maintainTemplate: undefined,
        detectionTemplate: undefined,
        serviceOrganization: undefined,
        warrantyCost: undefined,
        afterSalesPhone: undefined,
        contactName: undefined,
        contactPhone: undefined,
        equipmentTotalAmount: 0.0,
        equipmentUnitPrice: 0.0,
        deviceNumber: 0,
        warrantyPeriod: 0,
        contractEquipmentConfiguration: undefined,
        contractEquipmentCommonFault: undefined,
        errors: {},
        index: indexOf,
      }
      console.log('添加空数据....', record.index)
      this.contractEquipmentList.splice(indexOf, 0, record)
      this.$refs.contractEquipmentEditRef.edit(record)
    },
    //设备编辑完成后
    contractEquipmentEditOk(record) {
      console.log('更新现有项目1....', record.equipmentName)
      // 更新现有项目

      this.$set(this.contractEquipmentList, record.index, {
        ...this.contractEquipmentList[record.index],
        ...record,
      })
    },
    contractEquipmentClose(record) {
      console.log('contractEquipmentClose删除空数据2....', record.index)
      this.removeContractEquipmentRow(record.index)
    },
    //编辑设备清单
    editContractEquipmentRow(record, index) {
      record.index = index
      this.$refs.contractEquipmentEditRef.edit(record)
    },
    // 删除行
    removeContractEquipmentRow(index) {
      this.contractEquipmentList.splice(index, 1)
    },

    // 验证字段
    validateContractEquipmentField(record, field) {
      // 清除旧错误
      if (record.errors && record.errors[field]) {
        this.$delete(record.errors, field)
      }

      // 必填校验规则
      const requiredFields = [
        'equipmentName',
        'warrantyPeriod',
        'deviceNumber',
        'equipmentUnitPrice',
      ]
      if (requiredFields.includes(field) && !record[field]) {
        this.$set(
          record.errors,
          field,
          `${this.getContractEquipmentFieldTitle(field)}不能为空`
        )
      }
    },

    // 获取字段标题
    getContractEquipmentFieldTitle(field) {
      const column = this.contractEquipmentColumns.find(
        (col) => col.dataIndex === field
      )
      return column ? column.title : field
    },

    // END设备清单

    // START签约方
    // 添加新行
    addContractPartyRow(index) {
      if (this.hasContractPartyErrors) return
      var indexOf = index + 1
      this.contractPartyListIndex = indexOf
      var partyName = this.partyNameList[indexOf]
      console.log('partyName>>', partyName)
      this.contractPartyList.splice(indexOf, 0, {
        key: Date.now().toString(),
        contractId: undefined,
        partyName: partyName,
        institutionName: '',
        address: undefined,
        contactName: undefined,
        contactPhone: undefined,
        email: undefined,
        errors: {},
      })
    },

    // 删除行
    removeContractPartyRow(index) {
      this.contractPartyListIndex = index - 1
      this.contractPartyList.splice(index, 1)
    },

    // 验证字段
    validateContractPartyField(record, field) {
      // 清除旧错误
      if (record.errors && record.errors[field]) {
        this.$delete(record.errors, field)
      }

      // 必填校验规则
      const requiredFields = ['institutionName']
      if (requiredFields.includes(field) && !record[field]) {
        this.$set(
          record.errors,
          field,
          `${this.getContractPartyFieldTitle(field)}不能为空`
        )
      }
    },

    // 获取字段标题
    getContractPartyFieldTitle(field) {
      const column = this.contractPartyColumns.find(
        (col) => col.dataIndex === field
      )
      return column ? column.title : field
    },

    // END签约方

    add() {
      this.csh()
      this.edit()
      this.isDisabled = '2'
    },
    //初始化数据
    csh() {
      this.clause1 = ''
      this.clause2 = ''
      this.clause3 = ''
      this.clause4 = ''
      this.clause5 = ''
      ;(this.clause6 = 'hours'),
        (this.clause7 = ''),
        (this.clause8 = 'hours'),
        (this.clause9 = '')
      this.clause10 = ''
      this.clause11 = ''
      this.clause12 = ''
      this.clause13 = ''
      this.clause14 = ''
      getByDictCodeList({
        dictCode: 'INSTITUTION_NAME',
      }).then((res) => {
        var institutionNameList = res.result.data
        this.contractPartyList = [
          {
            key: Date.now().toString(),
            contractId: undefined,
            partyName: '甲方',
            institutionName: institutionNameList[0].itemText,
            address: undefined,
            contactName: undefined,
            contactPhone: undefined,
            email: undefined,
            errors: {},
          },
        ]
      })((this.contractEquipmentList = []))
      this.contractFundsSourceList = [
        {
          key: Date.now().toString(),
          contractId: undefined,
          fundsSource: undefined,
          sourceRatio: 0.0,
          amount: 0.0,
          errors: {},
        },
      ]
      this.contractPaymentTermList = [
        {
          key: Date.now().toString(),
          contractId: undefined,
          payNumber: '1',
          payRatio: 0,
          payMoney: 0.0,
          errors: {},
        },
      ]
      this.contractOtherList = [
        {
          key: Date.now().toString(),
          number: '1',
          otherKeyTerm: undefined,
          errors: {},
        },
      ]
    },
    moment,
    edit(record) {
      console.log('record.isDisabled?>>>', this.isDisabled)
      this.$nextTick(() => {
        this.$objToOverride(this.formInfo, record)
        if (this.formInfo.id) {
          this.isDisabled = '1'
          if (record.isDisabled) {
            this.isDisabled = record.isDisabled
          }
          getAction(this.url.getInfo, { id: record.id }).then((res) => {
            this.$nextTick(() => {
              this.formInfo = res.result.data

              //签约方
              if (this.formInfo.contractParty) {
                this.contractPartyList = JSON.parse(this.formInfo.contractParty)
              }

              //设备清单
              if (this.formInfo.contractEquipment) {
                this.contractEquipmentList = JSON.parse(
                  this.formInfo.contractEquipment
                )
              } else {
                this.contractEquipmentList = []
              }

              //资金来源
              if (this.formInfo.contractFundsSource) {
                this.contractFundsSourceList = JSON.parse(
                  this.formInfo.contractFundsSource
                )
              }

              //付款条件
              if (this.formInfo.contractPaymentTerm) {
                this.contractPaymentTermList = JSON.parse(
                  this.formInfo.contractPaymentTerm
                )
              }

              //器械运输、安装和验收
              if (this.formInfo.transportationInstallatio) {
                var transportationInstallatio = JSON.parse(
                  this.formInfo.transportationInstallatio
                )
                this.clause1 = transportationInstallatio.clause1
                this.clause2 = transportationInstallatio.clause2
                this.clause3 = transportationInstallatio.clause3
              }

              //质量保证及售后服务
              if (this.formInfo.qualityAssuranceAfterService) {
                var qualityAssuranceAfterService = JSON.parse(
                  this.formInfo.qualityAssuranceAfterService
                )
                this.clause4 = qualityAssuranceAfterService.clause4
                this.clause5 = qualityAssuranceAfterService.clause5
                this.clause6 = qualityAssuranceAfterService.clause6
                this.clause7 = qualityAssuranceAfterService.clause7
                this.clause8 = qualityAssuranceAfterService.clause8
                this.clause9 = qualityAssuranceAfterService.clause9
                this.clause10 = qualityAssuranceAfterService.clause10
                this.clause11 = qualityAssuranceAfterService.clause11
                this.clause12 = qualityAssuranceAfterService.clause12
                this.clause13 = qualityAssuranceAfterService.clause13
              }

              //其他服务条款
              if (this.formInfo.otherKeyTerm) {
                this.contractOtherList = JSON.parse(this.formInfo.otherKeyTerm)
              }

              this.contractAmountChange(this.formInfo.contractAmount)

              if (this.formInfo.warrantyStartPeriod) {
                this.warrantyPeriod = [
                  this.formInfo.warrantyStartPeriod,
                  this.formInfo.warrantyEndPeriod,
                ]
              }
            })
          })
        } else {
        }
      })
      this.visible = true
    },
    //供应商列表
    getSupplierList() {
      getAction(this.url.getSupplierList).then((res) => {
        this.supplierList = res.result.data
      })
    },
    // 确定
    handleSubmit(isSave) {
      // 触发表单验证
      this.confirmLoading = true
      this.$refs.ruleForm.validate((valid) => {
        console.log(valid)
        if (valid) {
          if (
            this.contractFundsSourceTotalSum > this.contractEquipmentTotalSum
          ) {
            this.$message.error('分项资金总值不等于成交总价!')
            this.confirmLoading = false
            return
          }
          if (this.contractPaymentTermTotalSum > 0) {
            if (
              this.contractPaymentTermTotalSum != this.formInfo.contractAmount
            ) {
              this.$message.error('付款期数总金额和付款总额不一致,请重新输入!')
              this.confirmLoading = false
              return
            }
          }

          //签约方
          if (this.contractPartyList) {
            this.formInfo.contractParty = JSON.stringify(this.contractPartyList)
          }

          //设备清单
          if (this.contractEquipmentList) {
            this.formInfo.contractEquipment = JSON.stringify(
              this.contractEquipmentList
            )
          }

          //资金来源
          if (this.contractFundsSourceList) {
            this.formInfo.contractFundsSource = JSON.stringify(
              this.contractFundsSourceList
            )
          }

          //付款条件
          if (this.contractPaymentTermList) {
            this.formInfo.contractPaymentTerm = JSON.stringify(
              this.contractPaymentTermList
            )
          }

          //器械运输、安装和验收
          this.formInfo.transportationInstallatio = JSON.stringify({
            clause1: this.clause1,
            clause2: this.clause2,
            clause3: this.clause3,
          })
          //质量保证及售后服务
          this.formInfo.qualityAssuranceAfterService = JSON.stringify({
            clause4: this.clause4,
            clause5: this.clause5,
            clause6: this.clause6,
            clause7: this.clause7,
            clause8: this.clause8,
            clause9: this.clause9,
            clause10: this.clause10,
            clause11: this.clause11,
            clause12: this.clause12,
            clause13: this.clause13,
          })
          //其他服务条款
          this.formInfo.isSave = isSave
          this.formInfo.contractClassification = this.contractClassification
          this.formInfo.otherKeyTerm = JSON.stringify(this.contractOtherList)
          postAction(this.url.saveInfo, this.formInfo)
            .then((res) => {
              this.$message.success('操作成功')
              this.$emit('ok', this.formInfo)
              console.log('XXLALSAS>>', this.isDisabled)
              if (this.isDisabled != '3') {
                this.close()
              }
            })
            .finally(() => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 关闭
    handleCancel() {
      this.close()
    },
    close() {
      this.$refs.ruleForm.resetFields()
      this.$objToReset(this.formInfo)
      this.$emit('close')
    },
    editorOk(val) {
      this.formInfo.content = val
    },
  },
}
</script>

<style scoped>
@import url('../../../../css/contract/devContractSave.css');

/* 处理选择器下拉图标颜色 */
.unit-select >>> .ant-select-arrow {
  color: rgba(0, 0, 0, 0.6);
}

.unit-select {
  width: 80px;
  border: none !important;
  box-shadow: none !important;
}

.unit-select >>> .ant-select-selector {
  border: none !important;
  padding-left: 8px !important;
}
</style>
